

import 'package:bot_toast/bot_toast.dart';
import 'package:dolqun_movies/Entities/LatestMovies.dart';
import 'package:dolqun_movies/Entities/Movie.dart';
import 'package:dolqun_movies/StateManagement/ModelProvider.dart';
import 'package:dolqun_movies/UI/Pages/Models/MainModel.dart';
import 'package:dolqun_movies/UI/Widgets/DolqunAppBar.dart';
import 'package:dolqun_movies/UI/Widgets/MovieView.dart';
import 'package:dolqun_movies/UI/Widgets/MyAnimatedRoute.dart';
import 'package:flutter/material.dart';

import 'DetailsPage.dart';

class SearchResultPage extends StatefulWidget {
  String keyword;
  SearchResultPage({this.keyword});

  @override
  State<StatefulWidget> createState() => _SearchResultState();
}

class _SearchResultState extends State<SearchResultPage> {
  var _oldPosition = 0.0;
  ScrollController _controller = ScrollController();
  List<Movie> movies = [];
  var pageIndex = 1;

  @override
  void initState() {
    _controller.addListener(this._listener);
    super.initState();
  }
  @override
  void dispose() {
    _controller.removeListener(this._listener);
    super.dispose();
  }
  void _listener() {
    var after = _controller.position.extentAfter;
    if (after == _oldPosition) return;
    _oldPosition = after;
    if (_oldPosition != 0) return;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var apiModel = ModelContainer.of<MainModel>(context).model;
    BotToast.showLoading();
    Widget buildingWidget = FutureBuilder<LatestResponse>(
      future: apiModel.api.getMoviesByKeyWord(this.widget.keyword, pageIndex++).then((value){
        movies = [...movies, ...value.data];
        BotToast.closeAllLoading();
        return Future.value(value);
      }),
      builder: (context, snapshot){
        if (snapshot.hasData) {
          if (movies.isEmpty) return Center(
            child: Text("No data about ${this.widget.keyword}."),
          );
          return ListView(
            controller: _controller,
            children: <Widget>[
              GridView(
                gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                    maxCrossAxisExtent: 150.0,
                    childAspectRatio: 0.6
                ),
                shrinkWrap: true,
                physics: ScrollPhysics(),
                children: movies.map((movie) => _buildMovieItem(context, movie)).toList(),
              )
            ],
          );
        }
        if (snapshot.hasError) return Center(child: Text("An error occurred whilte fetching data, there is the error message:\n ${snapshot.error.toString()}"),);
        return Center(
          child: Text("Waiting..."),
        );
      },
    );
    buildingWidget = Scaffold(
      appBar: DolqunAppBar(),
      body: buildingWidget,
    );
    return buildingWidget;
  }

  Widget _buildMovieItem(BuildContext context, Movie movie, {String heroTagBuilder(int id)}) {
    heroTagBuilder ??= (id) => id.toString();
    var tag = heroTagBuilder(movie.id);
    return Hero(
      tag: tag,
      child: MovieView(
        movie: movie,
        onTab: ()async {
          await Navigator.of(context).push(MyAnimatedRoute(builder: (context) => DetailsPage(movie: movie, heroTag: tag,)));
        },
      ),
    );
  }
}